import path from "path";
import fs from "fs";
import AdmZip from "adm-zip"; // 使用adm-zip库来处理ZIP文件
import xml2js from "xml2js";
import { deepClone, getRandomStr } from "./tools";

/**
 * 提取Excel文件中的图片
 * @param {string} filePath Excel文件路径
 * @param {string} dataList 解析出来的表格JSON
 * @returns {Promise<string>} 解析后的图片文件名
 */
export async function handleImportImage(
  filePath: string,
  dataList: any,
  imgFideldName: string = "imgUrl"
): Promise<any[]> {
  const dataListCopy = deepClone(dataList);

  /**
   * 获取id对应的文件名
   */
  async function getIdNameMap() {
    // 创建一个临时文件来解压
    const zip = new AdmZip(filePath);
    const files = zip.getEntries();

    const cellimages = files.filter((item) => item.name === "cellimages.xml")[0];
    const ridMap = await getIdMap(cellimages.getData().toString());
    if (!ridMap) {
      return
    }
    const cellimagesRels: any = files.find((item) => item.name === "cellimages.xml.rels");
    const idFileNameMap = await getImageName(ridMap, cellimagesRels.getData().toString());
    return { idFileNameMap, files };
  }

  /**
   * 找到对应的文件
   */
  async function findImg() {
    for (const item of dataListCopy) {
      const idString = item[imgFideldName];
      if (!idString) {
        continue;
      }

      let imgId = idString.match(/"([^"]+)"/);
      imgId = imgId[1];

      const fileName = idFileNameMap[imgId];
      const file: any = files.find((item) => item.name === fileName);

      if (file) {
        const storageFileName = getRandomStr() + path.extname(file.name);
        await fs.promises.writeFile(
          path.resolve(__dirname, "../../public/static/uploads/", storageFileName),
          file.getData()
        );
        item[imgFideldName] = "/static/uploads/" + storageFileName;
      }
    }
  }

  let idFileNameMap: any;
  let files: any;

  const idMap = await getIdNameMap();
  if (idMap) {
    idFileNameMap = idMap.idFileNameMap;
    files = idMap.files;
    await findImg();
  }
  return dataListCopy;
}

async function xmlToJson(xmlString: string) {
  const result = await xml2js.parseStringPromise(xmlString);
  return JSON.stringify(result, null, 4);
}

/**
 * 获取dispId对应的rId
 */
async function getIdMap(xmlString: string) {
  let data = JSON.parse(await xmlToJson(xmlString));
  const res = {};

  if (!data || !data["etc:cellImages"] || !data["etc:cellImages"]["etc:cellImage"]) {
    return;
  }
  data["etc:cellImages"]["etc:cellImage"].forEach((cellImage) => {
    const pic = cellImage["xdr:pic"][0];
    const cNvPr = pic["xdr:nvPicPr"][0]["xdr:cNvPr"][0]["$"];
    const blip = pic["xdr:blipFill"][0]["a:blip"][0]["$"];

    res[cNvPr.name] = blip["r:embed"];
  });
  return res;
}

/**
 * 通过rid获取图片名字
 */
async function getImageName(ridMap: any, xml: any) {
  let jsonData = JSON.parse(await xmlToJson(xml));

  const relationships = jsonData.Relationships.Relationship;
  const relationshipsArray = Array.isArray(relationships) ? relationships : [relationships];

  const extractedValues = relationshipsArray.map((relationship) => ({
    id: relationship.$.Id,
    target: path.basename(relationship.$.Target),
  }));

  const result = {};

  for (const key of Object.keys(ridMap)) {
    const item = ridMap[key];

    const b: any = extractedValues.find((val) => val.id === item);
    result[key] = b.target;
  }

  return result;
}
